<?php
include 'facebook.php';
include 'appinclude.php';
include 'schedule.inc.php';

// set up facebook api
$facebook = new Facebook($GLOBALS["api_key"], $GLOBALS["api_secret"]);
$facebook->require_frame();
$user = $facebook->require_login();

// establish link with mysql database
$link = @mysql_connect($GLOBALS["db_host"], $GLOBALS["db_user"], $GLOBALS["db_pass"]);
@mysql_select_db($GLOBALS["db_name"]);

// check if calendar in db
$sem = $GLOBALS["semester"];
$cal_res = mysql_query("SELECT cal_string from cal_strings WHERE uid=$user AND semester='$sem'");
$cal_url = mysql_real_escape_string($_POST["cal_url"]);

//added code to parse the schedule and add to the db
$valid = test_valid_ics($cal_url);
if($valid)
{
  $valid = parseAddClasses($user, $cal_url);
}

?>

<?php if($valid): ?>

<?php
mysql_query("DELETE FROM cal_strings where uid=$user AND semester='$sem'");
mysql_query("INSERT INTO cal_strings (uid, cal_string, semester) VALUES ('$user', '$matches[1][0]', '" . $GLOBALS['semester'] . "');");
$template_bundle_id = 113909604850;
$tokens = array(); 
$target_ids = array();
$body_general = '';
$facebook->api_client->feed_publishUserAction($template_bundle_id, $tokens , implode(',', $target_ids), $body_general);
print '<fb:redirect url="'.$GLOBALS["full_callback"].'/index.php?posted=1" />';
?>

<?php else: ?>

<?php
print '<fb:redirect url="'.$GLOBALS["full_callback"].'/settings.php?invalid=1" />';
?>


<?php endif; ?>